const mysql = require('./selfDB');
const request = require('request');
const config = require('./config');

const appid = config.appId;
const gettoken_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid + '&secret=' + config.appSecret;
//查询数据库是否有可用的token

function geToken(openId) {
  var openid = openId; //'用户号' , 

  return mysql.select('*').from('system_token')
    .where({ appid })
    .then(data => {
      if (data[0].appid) {//存在数据，校验useflag和有效期，停用的退出，超出有效期的，重新获取，有效期内的返回token
        var existtoken=data[0].token;
        return {
          status: '0',
          msg: data
        }
      } else {//重新获取token
        getnewtoken();
      }
    })
    .catch(e => {
      return {
        status: '-1',
        msg: "query error:" + e.message
      }
    })
}
//重新获取token
getnewtoken = function (openid) {
  console.log('getToken');
  var self = this;

  //更新状态和openid，判断返回的openid是否本人，若不是则提示系统繁忙/退出

  return new Promise((resolve, reject) => {
    console.log('进入Promise方法了');
    request({
      method: 'GET',
      url: gettoken_url
    }, function (err, res, body) {
      if (res) {
        resolve({
          isSuccess: true,
          data: JSON.parse(body) //data.data.access_token {"access_token":"ACCESS_TOKEN","expires_in":7200}
        });
      } else {
        console.log(err);
        reject({
          isSuccess: false,
          data: err
        });
      }
    })
  }).then(tokeninfo => {
    if (tokeninfo.isSuccess) {
      return {
        status: '0',
        msg: tokeninfo.data.access_token
      }
    } else {
      console.log('Promise请求数据出错', tokeninfo.data);
      return {
        status: '-1',
        msg: tokeninfo.data
      }
    }
  })
}

module.exports = { geToken }